﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace OCR.Function
{
    public class DiskSpaceManager
    {

        public static int GB = 1024 * 1024 * 1024;//定义GB的计算常量
        public static int MB = 1024 * 1024;//定义MB的计算常量
        public static int KB = 1024;//定义KB的计算常量
        public static bool IsDiskSpaceLow(DirectoryInfo directory)
        {
            var drive = new DriveInfo(directory.Root.FullName);
            Console.WriteLine("drive.AvailableFreeSpace: "+drive.AvailableFreeSpace);
            Console.WriteLine("drive.TotalFreeSpace: " + drive.TotalFreeSpace);
            Console.WriteLine("drive.TotalSize: " + drive.TotalSize);
            float temp_Total_GB = drive.TotalSize / GB;
            float temp_Remaining_GB = drive.AvailableFreeSpace / GB;
            Console.WriteLine((float)drive.AvailableFreeSpace / (float)drive.TotalSize);
            Console.WriteLine(temp_Remaining_GB / temp_Total_GB);
            //Console.WriteLine((temp_Remaining_GB / temp_Total_GB) < 0.5f);
            return temp_Remaining_GB / temp_Total_GB < 0.5f; // 1GB阈值
        }


        public static void GetOrderDirectories(string path,int deleteCount=0)
        {
            DirectoryInfo dirInfo = new DirectoryInfo(path);
            // 获取所有文件（按修改时间降序）
            FileInfo[] files = dirInfo.GetFiles("*", SearchOption.AllDirectories)
                                     .OrderByDescending(f => f.LastWriteTime)
                                     .ToArray();
            // 获取所有子文件夹（按创建时间降序）
            DirectoryInfo[] subDirectories = dirInfo.GetDirectories("*", SearchOption.AllDirectories)
                                                    .OrderByDescending(d => d.CreationTime)
                                                    .ToArray();
            for (int i = 0; i < subDirectories.Length; i++)
            {
                Console.WriteLine("subDirectories: "+subDirectories[i].Name);
            }

        }

        public static int batchSize = 30;     // 初始批次大小
        public static int baseDelay = 50;     // 基础延迟(毫秒)
        public static int maxCpuUsage = 70;   // CPU占用阈值

        // 系统监控
        public static PerformanceCounter cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");

        #region 删除核心逻辑
        public static void ProcessDeletion(string rootPath, int n)
        {
            try
            {
                //var candidates = GetOldestFolders(rootPath, n);  //最远天数的文件夹个数

                var candidates = GetNonRecentFoldersByTime(rootPath, n);//最近天数
                AppendLog($"找到 {candidates.Count} 个待删除文件夹");

                int total = candidates.Count;
                int processed = 0;

                foreach (var dir in candidates)
                {
                    AppendLog($"开始处理: {rootPath +"\\"+ dir.Name}");
                    DeleteDirectoryWithThrottle(dir.FullName, ref processed, total);
                    AppendLog($"完成删除: {rootPath + "\\" + dir.Name}", isSuccess: true);
                }
            }
            catch (Exception ex)
            {
                AppendLog($"操作终止: {ex.Message}", isError: true);
            }
        }
        public static List<DirectoryInfo> GetOldestFolders(string path, int n)
        {
            List<DirectoryInfo> directoryInfos = new DirectoryInfo(path)
                .GetDirectories()
                .OrderBy(d => d.LastWriteTime)
                .Take(n)
                .ToList();
            foreach (var item in directoryInfos)
            {
                Console.WriteLine("directoryInfos:"+ item.Name);
            }
            return directoryInfos;
        }
        public static List<DirectoryInfo> GetNonRecentFoldersByTime(string rootPath, int retainDays)
        {
            DateTime cutoffDate = DateTime.Now.AddDays(-retainDays);
            DirectoryInfo rootDir = new DirectoryInfo(rootPath);

            // 获取所有子目录
            DirectoryInfo[] allDirs = rootDir.GetDirectories();

            List<DirectoryInfo> oldFolders = new List<DirectoryInfo>();
            foreach (DirectoryInfo dir in allDirs)
            {
                if (dir.LastWriteTime < cutoffDate)
                {
                    oldFolders.Add(dir);
                }
            }
            foreach (var item in oldFolders)
            {
                Console.WriteLine("oldFolders:" + item.Name);
            }


            //DateTime cutoffDate = DateTime.Today.AddDays(-retainDays); // 精确到当天零点
            //var rootDir = new DirectoryInfo(rootPath);
            //var oldFolders = rootDir.GetDirectories("*", SearchOption.AllDirectories)
            //                        .Where(dir => dir.LastWriteTime < cutoffDate)
            //                        .Select(dir => dir)
            //                        .ToList();

            foreach (var item in oldFolders)
            {
                Console.WriteLine("oldFolders:" + item.Name);
            }
            return oldFolders;
        }
        #endregion

        #region 删除控制方法
        public static void DeleteDirectoryWithThrottle(string path, ref int processedCount, int total)
        {
            var fileQueue = new Queue<string>(Directory.EnumerateFiles(path, "*.*", SearchOption.AllDirectories));
            int totalFiles = fileQueue.Count;

            while (fileQueue.Count > 0)
            {
                AdjustSpeedParameters();

                int currentBatch = Math.Min(batchSize, fileQueue.Count);
                for (int i = 0; i < currentBatch; i++)
                {
                    ProcessFile(fileQueue.Dequeue());
                }

                processedCount += currentBatch;
                UpdateProgress(processedCount, totalFiles, total);

                Thread.Sleep(baseDelay);
            }

            // 删除空目录
            Directory.Delete(path, true);
        }

        public static void AdjustSpeedParameters()
        {
            float cpuUsage = cpuCounter.NextValue();
            if (cpuUsage > maxCpuUsage)
            {
                batchSize = Math.Max(10, batchSize - 5);
                baseDelay = Math.Min(500, baseDelay + 50);
            }
            else
            {//100
                batchSize = Math.Min(60, batchSize + 2);
                baseDelay = Math.Max(20, baseDelay - 10);
            }
        }
        #endregion

        #region 辅助方法
        public static void ProcessFile(string filePath)
        {
            try
            {
                File.SetAttributes(filePath, FileAttributes.Normal);
                File.Delete(filePath);
            }
            catch (Exception ex)
            {
                AppendLog($"文件删除失败: {Path.GetFileName(filePath)} - {ex.Message}", isError: true);
            }
        }

        public static void UpdateProgress(int current, int totalFiles, int totalFolders)
        {
            Console.WriteLine("删除文件进度: "+ (int)(current * 100f / totalFiles));
            //OCR_Form.oCR_Form.BeginInvoke(new Action(() =>
            //{
            //    progressBarFiles.Value = (int)(current * 100f / totalFiles);
            //    progressBarFolders.Value = (int)((progressBarFolders.Value + 100f / totalFolders) % 100);
            //}));
        }
        #endregion

        #region 日志系统
        public static void AppendLog(string message, bool isError = false, bool isSuccess = false)
        {
            var txtLog = OCR_Form.oCR_Form.richTB_State_PLC;
            OCR_Form.oCR_Form.BeginInvoke(new Action(() =>
            {
                string timestamp = DateTime.Now.ToString("HH:mm:ss.fff");
                Color color = Color.Silver;

                if (isError) color = Color.Silver;//Color.OrangeRed
                else if (isSuccess) color = Color.Silver;//Color.LimeGreen

                txtLog.SelectionStart = txtLog.TextLength;
                txtLog.SelectionColor = color;
                txtLog.AppendText($"[{timestamp}] {message}\n");
                txtLog.ScrollToCaret();
            }));
        }
        #endregion
    }

}
